package cn.sciento.farm.devicemanager.common.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 多线程保存独立数据
 */
public class BaseContextHandler {

    static final String CONTEXT_KEY_ID = "id";

    static final String CONTEXT_KEY_TENANT_ID = "tenant_id";


    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static Boolean isNull(){
        Map<String, Object> map = threadLocal.get();
        if(map == null){
            return true;
        }else {
            return false;
        }
    }

    public static Long getId() {
        Object value = get(CONTEXT_KEY_ID);
        return (Long) value;
    }

    public static String getTenantId() {
        Object value = get(CONTEXT_KEY_TENANT_ID);
        return (String) value;
    }






    public static void setTenantId(String tenantId) {
        set(CONTEXT_KEY_TENANT_ID, tenantId);
    }



    private static String returnObjectValue(Object value) {
        return value == null ? null : value.toString();
    }

    public static void remove() {
        threadLocal.remove();
    }

    public static void setId(Long id) {
        set(CONTEXT_KEY_ID, id);
    }


    public static String getObjectValue(Object obj) {
        return obj == null ? "" : obj.toString();
    }
}
